package org.boot.fast.dao;

import org.boot.fast.pojo.FileInfoDO;
import org.boot.fast.pojo.QueryCondition;
import org.boot.fast.repository.JdbcRepositoryUtil;
import org.boot.fast.util.ConverterUtil;
import org.boot.fast.util.MappingUtil;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Component
public class FileInfoDAO {

    private static final String TABLE = "fast_file_info";

    @Transactional(rollbackFor = Exception.class)
    public Long save(FileInfoDO fileInfoDO) {
        Map<String, Object> dataMap = MappingUtil.mappingToTable(ConverterUtil.convertToMap(fileInfoDO));
        return JdbcRepositoryUtil.insertBack(TABLE, dataMap);
    }

    @Transactional(rollbackFor = Exception.class)
    public int update(FileInfoDO fileInfoDO) {
        Map<String, Object> dataMap = MappingUtil.mappingToTable(ConverterUtil.convertToMap(fileInfoDO));
        List<QueryCondition> conditions = new ArrayList<>();
        conditions.add(new QueryCondition("id", "=", fileInfoDO.getId()));
        return JdbcRepositoryUtil.update(TABLE, dataMap, conditions);
    }

    @Transactional(rollbackFor = Exception.class)
    public int delete(Long id) {
        List<QueryCondition> conditions = new ArrayList<>();
        conditions.add(new QueryCondition("id", "=", id));
        return JdbcRepositoryUtil.delete(TABLE, conditions);
    }

    public FileInfoDO findOne(Long id) {
        return ConverterUtil.convert(
                MappingUtil.mappingToJava(
                        JdbcRepositoryUtil.findById(TABLE, id)
                ), FileInfoDO.class);
    }

    public List<FileInfoDO> findList(FileInfoDO fileInfoDO) {
        List<QueryCondition> conditions = new ArrayList<>();
        if(fileInfoDO != null){
            if (fileInfoDO.getId() != null) conditions.add(new QueryCondition("id", "=", fileInfoDO.getId()));
            if (fileInfoDO.getStatus() != null) conditions.add(new QueryCondition("status", "=", fileInfoDO.getStatus()));
            if (fileInfoDO.getFileKey() != null) conditions.add(new QueryCondition("file_key", "=", fileInfoDO.getFileKey()));
            if (fileInfoDO.getFileName() != null) conditions.add(new QueryCondition("file_name", "=", fileInfoDO.getFileName()));
            if (fileInfoDO.getFilePath() != null) conditions.add(new QueryCondition("file_path", "=", fileInfoDO.getFilePath()));
            if (fileInfoDO.getUploadUser() != null) conditions.add(new QueryCondition("upload_user", "=", fileInfoDO.getUploadUser()));
        }
        return ConverterUtil.convert(
                MappingUtil.mappingToJava(
                        JdbcRepositoryUtil.find(TABLE, conditions)
                ), FileInfoDO.class);
    }

}